package com.niannian.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

/**
 * 实体的工具类
 * 
 * 
 */
public class FileUtils {
	/**
	 * 设置属性值
	 * 
	 * @param field
	 * @param object
	 * @param fieldValue
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static void setValueToFiled(Field field, Object object,
			String fieldValue) throws IllegalArgumentException,
			IllegalAccessException {

		field.setAccessible(true);// 允许插入
		Class fieldType = field.getType();// 属性的类型

		if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {// int
			Integer value = Integer.parseInt(fieldValue);
			field.set(object, value);
		} else if (String.class == fieldType) {// string
			field.set(object, fieldValue);
		} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {// long
			Long value = Long.parseLong(fieldValue);
			field.set(object, value);
		} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {// float
			Float value = Float.parseFloat(fieldValue);
			field.set(object, value);
		} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {// short
			Short value = Short.parseShort(fieldValue);
			field.set(object, value);
		} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {// double
			Double value = Double.parseDouble(fieldValue);
			field.set(object, value);
		} else if (Character.TYPE == fieldType) {// char
			Character value = Character.valueOf(fieldValue.charAt(0));
			field.set(object, value);
		} else if (Date.class == fieldType) {// date
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				Date date = sdf.parse(fieldValue);
				field.set(object, date);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (Boolean.class == fieldType) {
			field.setBoolean(object,
					(Boolean.parseBoolean(String.valueOf(fieldValue))));
		}
	}

	public static void setDefValueToFiled(Field field, Object object)
			throws IllegalArgumentException, IllegalAccessException {

		field.setAccessible(true);// 允许插入
		Class fieldType = field.getType();// 属性的类型

		if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {// int
			Integer value = 0;
			field.set(object, value);
		} else if (String.class == fieldType) {// string
			field.set(object, "");
		} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {// long
			Long value = Long.parseLong("0");
			field.set(object, value);
		} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {// float
			Float value = Float.parseFloat("0");
			field.set(object, value);
		} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {// short
			Short value = Short.parseShort("0");
			field.set(object, value);
		} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {// double
			Double value = Double.parseDouble("0");
			field.set(object, value);
		} else if (Date.class == fieldType) {// date
			try {
				Date date = null;
				field.set(object, date);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (Boolean.class == fieldType) {
			field.setBoolean(object, false);
		}
	}

	/**
	 * 拿到指定的属性值
	 * 
	 * @param field
	 * @param object
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static void getValueFromField(Field field, Object object)
			throws IllegalArgumentException, IllegalAccessException {
		field.setAccessible(true);

		Class fieldType = field.getType();

		if (Integer.TYPE == fieldType || Integer.class == fieldType) {// int
			field.getInt(object);
		} else if (String.class == fieldType) {// string
			String.valueOf(field.get(object));
		} else if (Short.class == fieldType) {// short
			field.getShort(object);
		} else if (Long.class == fieldType) {// long
			field.getLong(object);
		} else if (Float.class == fieldType) {// float
			field.getFloat(object);
		} else if (Double.class == fieldType) {// double
			field.getDouble(object);
		} else if (Character.class == fieldType) {// char
			field.getChar(object);
		} else if (Date.class == fieldType) {// date
			String.valueOf(field.get(object));
		} else if (Boolean.class == fieldType) {// boolean
			field.getBoolean(object);
		}
	}

	public static Object getFieldValue(Field field, Object object)
			throws Exception {
		Object temp = null;
		field.setAccessible(true);
		Class fildType = field.getType();
		if (String.class == fildType || Character.class == fildType) {
			temp = String.valueOf(field.get(object));
		} else if (Integer.TYPE == fildType || Integer.class == fildType) {
			temp = field.getInt(object);
		} else if (boolean.class == fildType) {
			temp = field.getBoolean(object);
		} else if (Long.class == fildType) {
			temp = field.getLong(object);
		} else if (Float.class == fildType) {
			temp = field.getFloat(object);
		}
		return temp;
	}

	// 写入内存卡
	public static void writeBitmap(Bitmap bmp, Context context, String name) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		try {
			Write(baos.toByteArray(), context, name);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static File getAppExternalStoragePath() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				File file = new File(Environment.getExternalStorageDirectory()
						.getCanonicalPath() + "/xydr");
				if (!file.exists()) {
					file.mkdirs();
				}
				return file;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static File getCrashLogPath() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				File file = new File(Environment.getExternalStorageDirectory()
						.getCanonicalPath() + "/xydr/crash");
				if (!file.exists()) {
					file.mkdirs();
				}
				return file;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static File createTempFile(String prefix, String suffix) {
		File file = null;
		try {
			if (prefix.length() < 3) {
				prefix += "_tmp";
			}
		} catch (Exception e) {
			return null;
		}

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				File path = new File(Environment.getExternalStorageDirectory()
						.getCanonicalPath() + "/xydr/.temp/");
				if (!path.exists()) {
					path.mkdirs();
				}

				file = File.createTempFile(prefix, suffix, path);
			} catch (Exception e) {
				e.printStackTrace();
				file = null;
			}
		} else {
			try {
				file = File.createTempFile(prefix, suffix);
			} catch (Exception e) {
				e.printStackTrace();
				file = null;
			}
		}
		return file;
	}

	public static void Write(byte[] b, Context context, String nString)
			throws IOException {
		File cacheFile = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File sdCardDir = Environment.getExternalStorageDirectory();
			long time = Calendar.getInstance().getTimeInMillis();
			// String tiString = getFormatDate2YMDHMS(time);
			String fileName = nString + ".png";
			File dir = new File(sdCardDir.getCanonicalPath() + "/xydr");
			if (!dir.exists()) {
				dir.mkdirs();
			}
			cacheFile = new File(dir, fileName);
			Common.tip(context, "图片保存在内存卡下\"xydr\"文件夹中，请查看！", Toast.LENGTH_LONG);
			BufferedOutputStream bos = null;
			try {
				bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
				bos.write(b, 0, b.length);
				bos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Common.tip(context, "请检查内存卡是否有效");
		}
	}

	/**
	 * 返回年月日
	 * 
	 * @param time
	 * @return yyyy年MM月dd日 HH:mm:ss
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getFormatDate2YMDHMS(long time) {
		SimpleDateFormat format1 = new SimpleDateFormat(
				"yyyy年MM月dd日   HH时mm分ss秒");
		Date date = new Date(time);
		String startDateString = format1.format(date);
		return startDateString;
	}

	public static void WriteBitmap(byte[] b, Context context, String nString,
			String fileName) throws IOException {
		File cacheFile = null;
		// if
		// (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		// {
		File sdCardDir = context.getFilesDir();
		long time = Calendar.getInstance().getTimeInMillis();
		String tiString = getFormatDate2YMDHMS(time);
		File dir = new File(sdCardDir.getCanonicalPath() + "/Image");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		cacheFile = new File(dir, fileName);
		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
			bos.write(b, 0, b.length);
			bos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// } else {
		// Common.tip(context, "请检查内存卡是否有效");
		// }
	}

	public static void writeBitmapDEL(Bitmap bmp, Context context, String name,
			String fileName) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		try {
			WriteBitmap(baos.toByteArray(), context, name, fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void WriteHeadBitmap(byte[] b, Context context,
			String fileName, String path) throws IOException {
		File cacheFile = null;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		cacheFile = new File(dir, fileName);
		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
			bos.write(b, 0, b.length);
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void writeBitmapHead(Bitmap bmp, Context context,
			String fileName, String path) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		try {
			WriteHeadBitmap(baos.toByteArray(), context, fileName, path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getFileExtension(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int i = filename.lastIndexOf('.');
			if ((i > -1) && (i < -1 + filename.length()))
				filename = filename.substring(i);
		}

		filename = filename.toLowerCase();
		Log.i("getFileExtension", filename);
		// if (filename != ".jpg" && filename != ".jpeg" && filename != ".png"
		// && filename != ".gif") {
		// return ".png";
		// }
		return filename;
	}

	public static String getImageFileExtension(String filename) {
		try {
			if ((filename != null) && (filename.length() > 0)) {
				int i = filename.lastIndexOf('.');
				if ((i > -1) && (i < -1 + filename.length()))
					filename = filename.substring(i);
			}

			filename = filename.toLowerCase();
			Log.i("getFileExtension", filename);
			if (filename != ".jpg" && filename != ".jpeg" && filename != ".png"
					&& filename != ".gif") {
				return ".png";
			}
			return filename;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] getBytes(File file) {
		try {
			FileInputStream in = new FileInputStream(file);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			return out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static boolean saveBitmapJpeg(Bitmap bitmap, File saveFile,
			float angle) {
		try {
			FileOutputStream fos = new FileOutputStream(saveFile);

			if (angle != 0) {
				Matrix matrix = new Matrix();
				matrix.setRotate(angle);

				Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0,
						bitmap.getWidth(), bitmap.getHeight(), matrix, true);
				rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				rotateBitmap.recycle();
			} else {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			}
			fos.flush();
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void saveLocalPng(Bitmap bmp, Context context, String name) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		try {
			File cacheFile = null;
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = name + ".png";
				File dir = new File(sdCardDir.getCanonicalPath()
						+ "/xydr/qrcode");
				if (!dir.exists()) {
					dir.mkdirs();
				}
				cacheFile = new File(dir, fileName);
				BufferedOutputStream bos = null;
				bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
				bos.write(baos.toByteArray(), 0, baos.toByteArray().length);
				bos.close();
				Common.tip(context, "二维码已保存至Ischool_Image/" + fileName);
			} else {
				Common.tip(context, "二维码保存失败,请检查内存卡是否有效");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
